Rust logoRust Korea
Menu
<- Series contents

5장. 첫 번째 REST API — CRUD 애플리케이션 만들기

20 min read

This chapter has not been translated into English yet. The Korean original is shown below.

5장. 첫 번째 REST API — CRUD 애플리케이션 만들기

지금까지 배운 라우팅, 핸들러, 응답을 종합하여, 실제 동작하는 REST API를 만들어 보겠습니다. 이 장에서는 메모리에 데이터를 저장하는 간단한 ‘할 일(Todo)’ 관리 API를 단계적으로 구축합니다. 이 예제는 공식 axum examples의 todos 예제를 간소화한 버전입니다.

5.1 프로젝트 설정

먼저 프로젝트를 만들고 필요한 의존성을 추가합니다.

cargo new todo_api --bin
cd todo_api
cargo add axum
cargo add tokio --features full
cargo add serde --features derive
cargo add serde_json
cargo add uuid --features v4,serde
cargo add chrono --features serde
cargo add tower --features util
cargo add tower-http --features trace,cors
cargo add tracing
cargo add tracing-subscriber --features env-filter

Cargo.toml의 [dependencies] 섹션은 다음과 비슷할 것입니다.

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
uuid = { version = "1", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
tower = { version = "0.5", features = ["util"] }
tower-http = { version = "0.6", features = ["trace", "cors"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

5.2 데이터 모델 정의

할 일 항목을 표현하는 모델을 정의합니다. CREATE 요청용과 응답용을 분리하면 API 설계가 깔끔해집니다.

// src/models.rs

use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use uuid::Uuid;

// 데이터베이스에 저장되는 전체 Todo 모델
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Todo {
    pub id: Uuid,                  // 고유 식별자
    pub title: String,             // 제목
    pub completed: bool,           // 완료 여부
    pub created_at: DateTime<Utc>, // 생성 시간
}

// 생성 요청용 DTO (Data Transfer Object)
// id, created_at 등은 서버에서 자동 생성하므로 클라이언트가 보낼 필요가 없습니다.
#[derive(Debug, Deserialize)]
pub struct CreateTodo {
    pub title: String,
}

// 수정 요청용 DTO
// 모든 필드를 Option으로 두어 부분 업데이트를 지원합니다.
#[derive(Debug, Deserialize)]
pub struct UpdateTodo {
    pub title: Option<String>,
    pub completed: Option<bool>,
}

5.3 메모리 저장소 구현

데이터베이스 대신 메모리에 데이터를 저장하는 간단한 저장소를 만듭니다. 프로덕션에서는 데이터베이스를 사용하지만, 학습 목적으로는 메모리 저장소가 충분합니다.

// src/store.rs

use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;  // 비동기 읽기-쓰기 락
use uuid::Uuid;
use crate::models::Todo;

// 스레드 안전한 메모리 저장소
// Arc<RwLock<...>>로 감싸서 여러 요청이 동시에 안전하게 접근할 수 있습니다.
// - Arc: 원자적 참조 카운팅 (여러 소유권)
// - RwLock: 다중 읽기 / 단일 쓰기 락
#[derive(Clone)]
pub struct TodoStore {
    inner: Arc<RwLock<HashMap<Uuid, Todo>>>,
}

impl TodoStore {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    // 모든 Todo 조회
    pub async fn list(&self) -> Vec<Todo> {
        // read()는 읽기 락을 획득합니다. 여러 읽기가 동시에 가능합니다.
        let todos = self.inner.read().await;
        let mut list: Vec<Todo> = todos.values().cloned().collect();
        // 생성 시간순으로 정렬
        list.sort_by_key(|t| t.created_at);
        list
    }

    // 단일 Todo 조회
    pub async fn get(&self, id: Uuid) -> Option<Todo> {
        self.inner.read().await.get(&id).cloned()
    }

    // 새 Todo 생성
    pub async fn create(&self, title: String) -> Todo {
        // write()는 쓰기 락을 획득합니다. 쓰는 동안 다른 접근이 차단됩니다.
        let mut todos = self.inner.write().await;
        let todo = Todo {
            id: Uuid::new_v4(),
            title,
            completed: false,
            created_at: chrono::Utc::now(),
        };
        todos.insert(todo.id, todo.clone());
        todo
    }

    // Todo 수정
    pub async fn update(&self, id: Uuid, title: Option<String>, completed: Option<bool>) -> Option<Todo> {
        let mut todos = self.inner.write().await;
        let todo = todos.get_mut(&id)?;
        if let Some(t) = title { todo.title = t; }
        if let Some(c) = completed { todo.completed = c; }
        Some(todo.clone())
    }

    // Todo 삭제
    pub async fn delete(&self, id: Uuid) -> bool {
        self.inner.write().await.remove(&id).is_some()
    }
}

5.4 앱 상태 정의

여러 핸들러에서 공유할 상태를 정의합니다. Axum에서는 State 추출자로 상태에 접근합니다.

// src/state.rs

use crate::store::TodoStore;

// Clone을 파생해야 합니다 (State 추출자가 Clone을 요구합니다).
// TodoStore가 Clone이므로 AppState도 Clone이 됩니다.
#[derive(Clone)]
pub struct AppState {
    pub store: TodoStore,
}

impl AppState {
    pub fn new() -> Self {
        Self {
            store: TodoStore::new(),
        }
    }
}

5.5 핸들러 구현

이제 CRUD(생성, 조회, 수정, 삭제) 핸들러를 구현합니다. 각 핸들러는 적절한 HTTP 상태 코드와 JSON을 반환합니다.

// src/routes/todos.rs

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Json},
    routing::{get, post, delete, patch},
    Router,
};
use uuid::Uuid;
use serde::Serialize;

use crate::models::{CreateTodo, UpdateTodo, Todo};
use crate::state::AppState;

// 에러 응답을 위한 구조체
#[derive(Serialize)]
struct ErrorResponse {
    error: String,
}

// Todo 라우터를 생성하는 함수
pub fn router() -> Router<AppState> {
    Router::new()
        .route("/", get(list_todos).post(create_todo))   // GET, POST /todos
        .route("/{id}", get(get_todo)                    // GET /todos/{id}
            .patch(update_todo)                          // PATCH /todos/{id}
            .delete(delete_todo))                        // DELETE /todos/{id}
}

// ===== 핸들러들 =====

// 모든 Todo 목록 조회
// GET /todos
async fn list_todos(State(state): State<AppState>) -> Json<Vec<Todo>> {
    let todos = state.store.list().await;
    Json(todos)
}

// 새 Todo 생성
// POST /todos
// 요청 본문: {"title": "할 일 내용"}
async fn create_todo(
    State(state): State<AppState>,
    Json(input): Json<CreateTodo>,  // 요청 본문을 파싱
) -> (StatusCode, Json<Todo>) {
    // 입력 검증
    if input.title.trim().is_empty() {
        // 실제로는 에러 처리가 필요하지만, 여기서는 단순화합니다.
        return (
            StatusCode::BAD_REQUEST,
            Json(Todo {
                id: Uuid::nil(),
                title: String::new(),
                completed: false,
                created_at: chrono::Utc::now(),
            }),
        );
    }

    let todo = state.store.create(input.title).await;
    (StatusCode::CREATED, Json(todo))  // 201 Created
}

// 단일 Todo 조회
// GET /todos/{id}
async fn get_todo(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> Result<Json<Todo>, (StatusCode, Json<ErrorResponse>)> {
    state.store.get(id).await
        .map(Json)
        .ok_or_else(|| (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse {
                error: format!("Todo {}를 찾을 수 없습니다", id),
            }),
        ))
}

// Todo 수정
// PATCH /todos/{id}
// 요청 본문: {"title": "수정된 제목", "completed": true} (모두 선택적)
async fn update_todo(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Json(input): Json<UpdateTodo>,
) -> Result<Json<Todo>, (StatusCode, Json<ErrorResponse>)> {
    state.store.update(id, input.title, input.completed).await
        .map(Json)
        .ok_or_else(|| (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse {
                error: format!("Todo {}를 찾을 수 없습니다", id),
            }),
        ))
}

// Todo 삭제
// DELETE /todos/{id}
async fn delete_todo(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    if state.store.delete(id).await {
        Ok(StatusCode::NO_CONTENT)  // 204 No Content
    } else {
        Err((
            StatusCode::NOT_FOUND,
            Json(ErrorResponse {
                error: format!("Todo {}를 찾을 수 없습니다", id),
            }),
        ))
    }
}

5.6 앱 조립과 실행

// src/main.rs

mod models;
mod store;
mod state;
mod routes {
    pub mod todos;
}

use axum::Router;
use tower_http::trace::TraceLayer;
use tracing_subscriber;

#[tokio::main]
async fn main() {
    // tracing 로거 초기화
    // RUST_LOG=todo_api=debug,tower_http=debug 환경 변수로 로그 레벨 제어
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "todo_api=debug,tower_http=debug".into()),
        )
        .init();

    let state = state::AppState::new();

    // 라우터 조립
    let app = Router::new()
        .nest("/todos", routes::todos::router())
        .route("/health", axum::routing::get(|| async { "OK" }))
        .with_state(state)
        // 요청/응답 로깅 미들웨어
        .layer(TraceLayer::new_for_http());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();

    tracing::info!("서버가 http://localhost:3000 에서 수신 대기 중");
    axum::serve(listener, app).await.unwrap();
}

5.7 API 테스트

서버를 실행한 후 curl로 각 엔드포인트를 테스트해 봅니다.

# 서버 시작
cargo run

# 1. 새 Todo 생성
curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"title": "Axum 배우기"}'
# 응답: {"id":"...", "title":"Axum 배우기","completed":false,"created_at":"..."}

# 2. 모든 Todo 조회
curl http://localhost:3000/todos

# 3. 특정 Todo 조회 (ID는 위 응답에서 복사)
curl http://localhost:3000/todos/<ID>

# 4. Todo 수정
curl -X PATCH http://localhost:3000/todos/<ID> \
  -H "Content-Type: application/json" \
  -d '{"completed": true}'

# 5. Todo 삭제
curl -X DELETE http://localhost:3000/todos/<ID>

# 6. 존재하지 않는 Todo 조회 (404 확인)
curl http://localhost:3000/todos/00000000-0000-0000-0000-000000000000
# 응답: {"error":"Todo ...를 찾을 수 없습니다"}

5.8 개선점과 다음 단계

이 예제는 학습 목적으로 단순화했습니다. 프로덕션 API로 발전시키려면 다음을 추가해야 합니다.

  • 영구 저장소: PostgreSQL, SQLite 등 데이터베이스 연동
  • 입력 검증: validator 크레이트로 필드 검증
  • 인증: JWT나 세션 기반 인증
  • 페이지네이션: 대량 데이터 처리
  • 에러 처리: thiserror로 구조화된 에러 타입
  • 테스트: 단위/통합 테스트 작성
  • 문서화: OpenAPI/Swagger 문서 자동 생성
  • 로깅: 구조화된 로깅과 모니터링

이 책의 후속 장들에서 이 모든 주제를 다룹니다. 2부에서는 추출자와 상태 관리를 깊이 있게, 3부에서는 데이터베이스와 실전 API 설계를, 4부에서는 인증과 보안을 다룹니다.

5.9 요약

이 장에서는 간단한 Todo REST API를 처음부터 끝까지 구축해 보았습니다. 데이터 모델 정의, 메모리 저장소 구현, 상태 관리, CRUD 핸들러 작성, 라우터 조립, 그리고 API 테스트까지 전체 과정을 살펴봤습니다. 이 예제는 Axum 애플리케이션의 전형적인 구조를 보여주며, 이후 장들에서 각 요소를 더 깊이 파고들 것입니다.

제1부를 마친 것을 축하합니다! 이제 Axum의 기본 사용법을 익혔습니다. 2부에서는 추출자, 상태 관리, 미들웨어, 에러 처리 등 핵심 개념을 깊이 있게 다루겠습니다.

Log in to save progress<- Back to series contents
<- Previous chapter
4장. 핸들러와 응답 — 요청을 처리하고 결과를 반환하기
Next chapter (🔒) ->
6장. 추출자 (Extractors) — 선언적 요청 파싱의 마법